/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is ThumbsDown.
 *
 * The Initial Developer of the Original Code is Atte Kemppilä.
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */


const EXPORTED_SYMBOLS = ["Context"];

const Cu = Components.utils;

Cu.import("resource://thumbsdown/ThumbsDown.jsm");
Cu.import("resource://thumbsdown/util.jsm");


function Context()
{
    this._isActive = false;
    this.range = null;
    this.thumbCtxs = [];
}

Context.prototype =
{
    get isActive() { return this._isActive; },
    set isActive(value)
    {
        if (value)
            this._isActive = true;
        else
        {
            for each (let thumbCtx in this.thumbCtxs)
                thumbCtx.thumbnail.highlight(false);
            
            this._isActive = false;
            this.range = null;
            this.thumbCtxs = [];
        }
    },
    
    isSelected: function(thumbnail)
    {
        for each (thumbCtx in this.thumbCtxs)
            if (thumbnail.isSame(thumbCtx.thumbnail))
                return true;
        
        return false;
    },
    
    toggleThumbnails: function(thumbnails)
    {
        let indexes = [];
        for each (let thumbnail in thumbnails)
            for (let i = 0; i < this.thumbCtxs.length; i++)
                if (thumbnail.isSame(this.thumbCtxs[i].thumbnail))
                    indexes.push(i);
        
        if (indexes.length > 0)
            return this.deselectThumbnails(indexes);
        else
            return this._selectThumbnails(thumbnails);
    },
    
    selectThumbnails: function(thumbnails)
    {
        thumbnails = [t for each (t in thumbnails) if (! this.isSelected(t))];
        return this._selectThumbnails(thumbnails);
    },
    
    _selectThumbnails: function(thumbnails)
    {
        var selected = [];
        for each (var thumbnail in thumbnails)
        {
            let script = ThumbsDown.ScriptManager.lookup(thumbnail);
            if (script)
            {
                selected.push(new ThumbnailContext(thumbnail, script));
                thumbnail.highlight(true);
            }
        }
        
        Array.prototype.push.apply(this.thumbCtxs, selected);
        return (selected.length > 0);
    },
    
    deselectThumbnails: function(indexes)
    {
        indexes = indexes.slice();
        indexes.sort();
        indexes.reverse();
        
        for each (let index in indexes)
        {
            let thumbCtx = this.thumbCtxs.splice(index, 1)[0];
            thumbCtx.thumbnail.highlight(false);
        }
        
        return (indexes.length > 0);
    },
    
    download: function()
    {
        let thumbCtxs = this.thumbCtxs.slice();
        
        ThumbsDown.getDownloadManager(function(downloadManager)
        {
            let downloadCtx = new DownloadContext(downloadManager);
            let callback = function(_thumbCtxs) { downloadCtx.download(_thumbCtxs); }
            ThumbsDown.eval(thumbCtxs, callback);
        });
        
        this.isActive = false;
    },
    
    startRange: function(element)
    {
        let doc = element.ownerDocument;
        let range = doc.createRange();
        range.setStartBefore(element);
        this.range = range;
    },
    
    endRange: function(element)
    {
        // ensure that start and end element are in correct order
        if (this.range.comparePoint(element, 0) >= 0)
            this.range.setEndAfter(element);
        else
        {
            let oldRange = this.range;
            this.startRange(element);
            this.range.setEnd(oldRange.startContainer, oldRange.startOffset + 1);
        }
        
        let range = this.range;
        this.range = null;
        return range;
    },
}


function ThumbnailContext(thumbnail, script)
{
    this.thumbnail = thumbnail;
    this.thumbnailUrl = thumbnail.thumbnailUrl;
    this.script = script;
    this.targets = null;
    this.error = null;
    this.callback = null;
}

ThumbnailContext.prototype =
{
    get resolved()
    {
        return (this.targets || this.error);
    },
    
    dispose: function()
    {
        this.thumbnail = null;
        this.callback = null;
    }
}


function DownloadContext(downloadManager)
{
    this.downloadManager = downloadManager;
    this.timestamp = new Date();
    this.downloadedUrls = {};
}

DownloadContext.prototype =
{
    download: function(thumbCtxs)
    {
        if (thumbCtxs.length == 0)
            return;
        
        // flatten thumbCtxs.targets to targets
        let targets = [];
        for each (let thumbCtx in thumbCtxs)
            if (thumbCtx.targets)
            {
                Array.prototype.push.apply(targets, thumbCtx.targets);
                
                thumbCtx.script.lastUsed = this.timestamp;
                thumbCtx.script.counter++;
            }
        
        // collect unique target urls within this download context
        let uniqueTargets = [];
        for each (let target in targets)
        {
            if (! (target.url in this.downloadedUrls))
                uniqueTargets.push(target);
            
            this.downloadedUrls[target.url] = true;
        }
        
        if (uniqueTargets.length > 0)
            this.downloadManager.download(uniqueTargets);
    },
}
